import win32com,os
from win32com.client import Dispatch, constants
class WordApp:
    def __init__(self):
        self.app = win32com.client.DispatchEx('Word.Application')
        self.app.Visible = 0
        self.app.DisplayAlerts = 0
    def setVisible(self,isVisible=False):
        if isVisible:
            self.app.Visible=1
        return self.app.Visible
    def replaceStr(self,oldstr:str,newstr:str):
        self.app.Selection.Find.ClearFormatting()
        self.app.Selection.Find.Replacement.ClearFormatting()
        self.app.Selection.Find.Execute(oldstr, False, False, False, False, False, True, 1, True,
                                        newstr, 2)
    def save(self):
        self.app.ActiveDocument.Save()
    def saveAs(self,path="example.docx"):
        self.app.ActiveDocument.SaveAs(path)
    def open(self,file:str=None):
        self.file=file
        if self.file==None:
            print("未发现文档，新建一个文档")
            self.doc = self.app.Documents.Add()
        else:
            self.doc=self.app.Documents.Open(file)
    def getText(self):
        text=""
        for i in range(self.doc.Paragraphs.Count):
            print(self.doc.Paragraphs[i].Range)
            try:
                text += self.doc.Paragraphs[i].Range
            except Exception as err:
                pass
        return text
    def insertPic(self,src):
        self.app.Selection.InlineShapes.AddPicture(src)
    def quit(self):
        self.app.Quit()
    def selectAll(self):
        self.app.Selection.WholeStory()
    def getTextCount(self):
        return self.app.ActiveDocument.Characters.Count
    def getParagraphsCount(self):
        return self.app.ActiveDocument.Paragraphs.Count
    def close(self):
        self.doc.Close()
if __name__ == '__main__':
    app=WordApp()
    app.open(r"C:\Users\Administrator\Desktop\病历自动生成\病历书写模板.docx")
    初步诊断="""
    1.高血压
    2.糖尿病
    3.不稳定型心绞痛 心功能II级
    """
    姓名='''高凯'''
    主诉='腹泻12天'
    app.setVisible(True)
    app.replaceStr("$初步诊断$",初步诊断)
    app.replaceStr("$姓名$",姓名)
    app.replaceStr("$主诉$",主诉)
    app.saveAs(f"{姓名}99.docx")
    app.close()
    app.quit()
    #app.saveAs()
    #app.quit()